package com.realbrand.net.realbrandpay.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.realbrand.net.realbrandpay.APP;
import com.realbrand.net.realbrandpay.R;
import com.realbrand.net.realbrandpay.api.HTTPAPI;
import com.realbrand.net.realbrandpay.bean.PickCodeBean;
import com.realbrand.net.realbrandpay.bean.ShopcarBean;
import com.realbrand.net.realbrandpay.inter.IScanCommodity;
import com.realbrand.net.realbrandpay.ui.activity.shopcar.CommodityDetailsActivity;
import com.realbrand.net.realbrandpay.untils.Static;
import com.realbrand.net.realbrandpay.zxing.app.CaptureActivity;
import com.realbrand.net.realbrandpay.zxing.util.L;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by lenovo on 2018/9/27.
 */

public class PickCodeOneAdapter extends BaseAdapter {
    public List<PickCodeBean> data;
    Context mContext;
    LayoutInflater inflater;

    public PickCodeOneAdapter(List<PickCodeBean> data, Context mContext) {
        this.data = data;
        this.mContext = mContext;
        inflater = LayoutInflater.from(mContext);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        PickViewHolder holder = null;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item_one_pickcode, parent, false);
            holder = new PickViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (PickViewHolder) convertView.getTag();
        }
        String[] split = data.get(position).getImgUrl().split(",");
        Picasso.with(mContext).load(split[0] + split[1]).into(holder.img);
        holder.tv_name.setText(data.get(position).getGoodsName());
        holder.tv_store.setText(data.get(position).getStoreName());
        holder.tv_address.setText(data.get(position).getStoreAddress());
        holder.tv_price.setText(data.get(position).getPrice());
        holder.tv_sum.setText("x" + data.get(position).getSum());
        final List<String> list = data.get(position).getGoodsScanList();
        PickCodeTwoAdapter twoAdapter = new PickCodeTwoAdapter(list, inflater);
        holder.listView.setAdapter(twoAdapter);
        setListViewHeightBasedOnChildren(holder.listView);
        holder.listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                getScanData(list.get(position));
            }
        });
        return convertView;
    }

    /**
     * 用点击的商品码请求数据
     *
     * @param s
     */
    private void getScanData(final String s) {
        JSONObject jsonObjec = new JSONObject();
        try {
            jsonObjec.put("SOURCE", "CaptureActivity");
            jsonObjec.put("CREDENTIALS", "0");
            jsonObjec.put("TERMINAL", "1");
            jsonObjec.put("INDEX", Static.getDay());
            jsonObjec.put("METHOD", "GetCommodityInfo");
            jsonObjec.put("CommodityCode", s);
            L.d("ssssssss", s.toString());
            RequestBody body = RequestBody.create(HTTPAPI.JSON, jsonObjec.toString());
            Retrofit retrofit = new Retrofit.Builder().baseUrl(HTTPAPI.BASE_URL).build();
            IScanCommodity iScanCommodity = retrofit.create(IScanCommodity.class);
            Call<ResponseBody> call = iScanCommodity.getDatas(body);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String result = response.body().string();
                        L.d(L.TAG,"结果"+result);
                        if (TextUtils.isEmpty(result)) {
                            Static.toast(mContext, "网络繁忙");
                        } else {
                            JSONObject object = new JSONObject(result);
                            String scanState = object.getString("ScanState");
                            JSONObject json = object.getJSONArray("DATA").getJSONObject(0);
                            String commodityName = json.getString("CommodityName");
                            String supplyMoney = json.getString("SupplyMoney");
                            String enterpriseName = json.getString("EnterpriseName");
                            String UserAdress = json.getString("UserAddress");
                            String activationtime = json.getString("ActivationTime");
                            String productionAddress = json.getString("ProductionAddress");
                            String commodityProfile = json.getString("CommodityProfile");
                            String filePath = json.getString("FilePath");
                            String applyUser = json.getString("UserAccount");
                            String scanFrequency = json.getString("ScanFrequency");
                            JSONArray bankName = json.getJSONArray("BankName");
                            String scanTime = object.getString("ScanTime");
                            for (int i = 0; i < bankName.length(); i++) {
                                if (bankName.getString(i).equals("微信")) {
                                    APP.supportWX = true;
                                } else if (bankName.getString(i).equals("支付宝")) {
                                    APP.supportAlipay = true;
                                } else {
                                    APP.supportAlipay = false;
                                    APP.supportWX = false;
                                }
                            }
                            ShopcarBean bean = new ShopcarBean();
                            bean.setName(commodityName);
                            bean.setDrawableId(filePath);
                            bean.setAdress(UserAdress);
                            bean.setPrice(supplyMoney);
                            bean.setScan(s);
                            bean.setStore(enterpriseName);
                            bean.setActivationTime(activationtime);
                            bean.setProductionAdress(productionAddress);
                            bean.setCommodityProfile(commodityProfile);
                            bean.setApplyUser(applyUser);
                            bean.setScanStatte(scanState);
                            bean.setScanFrequency(scanFrequency);
                            bean.setScanTime(scanTime);
                            Intent intent = new Intent(mContext, CommodityDetailsActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("bean", bean);
                            intent.putExtras(bundle);
                            mContext.startActivity(intent);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Static.toast(mContext, "网络繁忙"+e.toString());
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    Static.toast(mContext, "网络繁忙");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    class PickViewHolder {
        ImageView img;
        TextView tv_name;
        TextView tv_store;
        TextView tv_address;
        TextView tv_price;
        TextView tv_sum;
        ListView listView;

        public PickViewHolder(View view) {
            img = (ImageView) view.findViewById(R.id.pickCode_itemOne_iv_img);
            tv_name = (TextView) view.findViewById(R.id.pickCode_itemOne_tv_name);
            tv_store = (TextView) view.findViewById(R.id.pickCode_itemOne_tv_store);
            tv_address = (TextView) view.findViewById(R.id.pickCode_itemOne_tv_address);
            tv_price = (TextView) view.findViewById(R.id.pickCode_itemOne_tv_price);
            tv_sum = (TextView) view.findViewById(R.id.pickCode_itemOne_tv_sum);
            listView = (ListView) view.findViewById(R.id.shopcarElvItem_listView);
        }
    }

    public void setListViewHeightBasedOnChildren(ListView listView) {
// 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
// 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() *
                (listAdapter.getCount() - 1));
// listView.getDividerHeight()获取子项间分隔符占用的高度
// params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }
}
